package com.suql.networktools.interceptor

import com.suql.networktools.AppPreference

import java.io.IOException

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * Created by Calm on 2017/12/14.
 * HeaderInterceptor
 */

class HeaderInterceptor : Interceptor {
//    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url().url().path
        val builder = request.newBuilder()
        // 登陆：从response取出cookie，并存储到SP；非登陆：从SP取出cookie，并设置到request中
        if (url != "/mobile/login") {
            builder.addHeader("Cookie", AppPreference.getString(AppPreference.LOGIN_COOKIE, ""))
        }
        if (url == "/mobile/login") {
            val response = chain.proceed(chain.request())
            if (!response.headers("Set-Cookie").isEmpty()) {
                for (header in response.headers("Set-Cookie")) {
                    AppPreference.putString(AppPreference.LOGIN_COOKIE, header)
                }
            }
        }
        return chain.proceed(builder.build())
    }
}
